package cn.hy.util;

import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionSynchronization;
import org.springframework.transaction.support.TransactionSynchronizationManager;

/**
 * 如何处理事务回调  处理分布式事务
 *
 * 还有一种方式
 * TransactionalEventListener 注解处理
 */
public class TransactionUtils {

    public static void doAfterTransaction(DoTransactionCompletion doTransactionCompletion) {
        if (TransactionSynchronizationManager.isActualTransactionActive()) {
            TransactionSynchronizationManager.registerSynchronization(doTransactionCompletion);
        }
    }


    @Transactional
    public void doTx() {
        TransactionUtils.doAfterTransaction(new DoTransactionCompletion(()->{
            // send mq .. RPC ..
        }));
        // end transaction ..
    }

}

class DoTransactionCompletion implements TransactionSynchronization {

    private final Runnable runnable;

    public DoTransactionCompletion(Runnable runnable) {
        this.runnable = runnable;
    }

    @Override
    public void afterCompletion(int status) {
        if (status == TransactionSynchronization.STATUS_COMMITTED) {
            this.runnable.run();
        }
    }
}